﻿using System;
using System.Collections.Specialized;
using System.Reflection;
using AFI.Speargun.Web.Core;
using AFI.Speargun.Web.Models;
using System.Collections.Generic;
using System.Web.Mvc;

namespace AFI.Speargun.Web.Core
{
    [Serializable]
    public class AssetEntryAdditionalDefinitionSchema : List<AssetEntryAdditionalDefinitionField>
    {
        public AssetEntryAdditionalDefinitionSchema()
        {

        }

        public AssetEntryAdditionalDefinitionSchema(FormCollection form)
        {
            this.LoadProperties();

            string[] keys = form.AllKeys;
            foreach (var i in keys)
            {
                // key_prop
                string[] s = i.Split('_');

                if (s.Length != 2)
                    throw new ArgumentException();

                AssetEntryAdditionalDefinitionField field = this.Find(f => f.FieldName == s[0]);

                PropertyInfo property = field.GetType().GetProperty(s[1]);
                if (property == null)
                    throw new ArgumentException();

                string originalValue = form[i];
                if (property.PropertyType == typeof(bool))
                    originalValue = originalValue.Split(',')[0];

                object value = Convert.ChangeType(originalValue, property.PropertyType);

                property.SetValue(field, value, null);
            }
        }

        public void LoadProperties()
        {
            Type t = typeof(AssetEntryAdditional);
            PropertyInfo[] properties = t.GetProperties();

            foreach (var i in properties)
            {
                if (i.PropertyType == typeof(Guid))
                    continue;

                AssetEntryAdditionalDefinitionField field = new AssetEntryAdditionalDefinitionField();
                field.FieldName = i.Name;

                this.Add(field);
            }
        }
    }

    [Serializable]
    public class AssetEntryAdditionalDefinitionField
    {
        public AssetEntryAdditionalDefinitionField()
        {
            this.FieldName = String.Empty;
            this.Enable = false;
            this.Appellation = String.Empty;
            this.Remark = String.Empty;
            this.Order = Byte.MaxValue;
        }

        public string FieldName { get; set; }
        public bool Enable { get; set; }
        public string Appellation { get; set; }
        public string Remark { get; set; }
        public int Order { get; set; }
    }
}
